package com.cg.bank.web.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.cg.bank.domain.User;

/**
 * 抽象Action
 *
 * @author chunge
 * @version 1.0
 */
public class BaseAction extends DispatchAction {
	/**
	 * 用户登录成功设定 <strong>session key</strong>
	 */
	protected static final String USERSESSIONFLAG = "user";
	
	/**
	 * 用于存储不敏感action(免验证访问) List容器
	 */
	private List<String> accessActionList = new ArrayList<>();
	/**
	 * 用于接收Action的<strong>参数名</strong>
	 */
	protected static final String ACTIONNAME = "a";
	
	/**
	 * 定义ROOT账户
	 */
	protected static final String ROOTACCOUNT = "YOUR ROOT ACCOUNT";
	
	public BaseAction() {
		// 添加允许请求的Action
		adddAccessURI();
	}

	/**
	 * 添加允许请求的Action
	 */
	private void adddAccessURI() {
		// 读取配置文件中不敏感action(允许直接访问action)
		InputStream in = this.getClass().getClassLoader().getResourceAsStream("../config/filter/accessAction.properties");
		Properties properties = new Properties();
		try {
			properties.load(in);
			Collection<Object> collection = properties.values();
			for (Object value : collection) {
				accessActionList.add(value.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 复写父类execute，添加请求权限验证
	 * 
	 * @param mapping actionMapping
	 * @param form 表单bean
	 * @param request request请求
	 * @param response response
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String action = request.getParameter(ACTIONNAME);
		// action非法存在
		if (action == null || action.length() < 3) {
			return mapping.findForward("index");
		}
		
		// 不在允许Action请求范围内需要请求权限验证
		if (!accessActionList.contains(action)) {
			User user =(User) request.getSession().getAttribute(USERSESSIONFLAG);
			if (user == null) {
				return mapping.findForward("loginRedirect");
			}
		} 
		// 允许Action请求，请求权限验证通过情况下，可访问对应Action
		return super.execute(mapping, form, request, response);
	}
	
}